"use strict";
const common_vendor = require("../../../common/vendor.js");
const api_user_index = require("../../../api/user/index.js");
const utils_auth_index = require("../../../utils/auth/index.js");
const useUserStore = common_vendor.defineStore("user", {
  state: () => ({
    user_id: "",
    user_name: "江阳小道",
    avatar: "",
    token: ""
  }),
  getters: {
    userInfo(state) {
      return { ...state };
    }
  },
  actions: {
    // 设置用户的信息
    setInfo(partial) {
      this.$patch(partial);
    },
    // 重置用户信息
    resetInfo() {
      this.$reset();
    },
    // 获取用户信息
    async info() {
      const result = await api_user_index.getUserProfile();
      this.setInfo(result);
    },
    // 异步登录并存储token
    login(loginForm) {
      return new Promise((resolve, reject) => {
        api_user_index.login(loginForm).then((res) => {
          const token = res.token;
          if (token) {
            utils_auth_index.setToken(token);
          }
          resolve(res);
        }).catch((error) => {
          reject(error);
        });
      });
    },
    // Logout
    async logout() {
      await api_user_index.logout();
      this.resetInfo();
      utils_auth_index.clearToken();
    },
    // 小程序授权登录
    authLogin(provider = "weixin") {
      return new Promise((resolve, reject) => {
        common_vendor.index.login({
          provider,
          success: async (result) => {
            if (result.code) {
              const res = await api_user_index.loginByCode({ code: result.code });
              resolve(res);
            } else {
              reject(new Error(result.errMsg));
            }
          },
          fail: (err) => {
            console.error(`login error: ${err}`);
            reject(err);
          }
        });
      });
    }
  }
});
exports.useUserStore = useUserStore;
